define(['zepto', 'utils', 'JST'], function($, utils, JST){
  return {
  	init: function(_CTX_, currentOffer, productType) {
      this._CTX_ = _CTX_
  	  this.currentOffer = currentOffer 
  	  this.productType = productType
      this.model = {}
      var $code = $('[data-selected-discount-code]')
      if ($code && $code.length) {
        this.model.selectedDiscountCode = parseInt($code.data('selected-discount-code'))
      }
  	  this.$discountCodeSelect = $('[href="#discount-code-select"]')
  	  this.$discountCodeSelect.length ? this.bindDiscountCodeBindingAction() : void 0

  	},

  	bindDiscountCodeBindingAction: function() {

  	  var that = this

  		this.$discountCodeSelect.on('click', function(e) {
  			e.preventDefault()
  			
            var defer = that.compileDiscountCodeSelectPage()
            $.when(defer).done(function($page) {
              $.push.transitionIn($page)
            })

  		})

  	},
  	
  	compileDiscountCodeSelectPage: function() {

    	  var that = this,
            deferPage = $.Deferred()

          var $page = $(JST.discountCodeSelectTpl())

          // Bind coupon page event
          that.bindDiscountCodeSelecttionPageEvent($page)

          deferPage.resolve($page)

        return deferPage.promise()
    },

    bindDiscountCodeSelecttionPageEvent:  function($page) {
      var that = this,
          $discountCode = $('input[name="discountCode"]', $page)
      $page.on('click', '.code-submit', function(e) {
        var id = parseInt(e.currentTarget.value)
        var discountCode = $discountCode.val().trim()
        
        if(discountCode == "") {
        	$.toast('折扣码不能为空');
        } else {
        	
        	that.model.selectedDiscountCode = discountCode

        var validateCode = that.validateDiscountCode(discountCode)
        
        that.$discountCodeSelect.trigger('selected:activity:discountCode', [$page, id, that.discountCode])

        // Transition out round selection page
        $.when(validateCode).done(function(data) {
        	$.push.transitionOut($page, {
                beforeTransition: function() {
                  that.$discountCodeSelect.find('.item-inner').empty()
                  that.$discountCodeSelect.find('.item-inner').append(JST.discountCodeItemTpl({'discount': (data.discount/100).toFixed(2), 'amount': data.discount, 'discountCode': data.discountCode}))
                  that.$discountCodeSelect.trigger('discountCode:change:event')
                }
              })
        })
        }
        
      })
    },

    validateDiscountCode: function(code) {
        var defer = $.Deferred(),
            url = this._CTX_.root + '/shop/discount-code?code=' + code + '&price=' + this.currentOffer + '&type=' + this.productType

        // Show request indicator
        $.showIndicator()
        // Request for rounds data
        $.ajax({
          'type': 'GET',
          'url': url,
          'cache': false
        }).done(function(response) {
          $.hideIndicator()  // Hide request indicator
          utils.processResult(response, function(result) {
            defer.resolve(result.data)
          }, function(result) {
            $.toast(result.message || '验证折扣码失败')
          })
        })

        return defer.promise()
      }
  }
})